﻿using douban.Core.Apis;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Windows.Networking;
using Windows.Web.Http;
using Windows.Web.Http.Headers;
using HttpClient = Windows.Web.Http.HttpClient;

namespace douban.Core.Utils
{
    public class WebUtil
    {
        public static async Task<string> Get(string url, IEnumerable<KeyValuePair<string, string>> queryData = null, Action<HttpClient> buildHeaders=null)
        {
            var httpClient = new HttpClient();
            httpClient = BuildHeader(ref httpClient);
            buildHeaders?.Invoke(httpClient);

            if (queryData != null)
                url = BuildUriQuery(url, queryData);

            return await httpClient.GetStringAsync(new Uri(url));
        }

    
        public static async Task<string> Post(string url, IEnumerable<KeyValuePair<string, string>> data, IEnumerable<KeyValuePair<string, string>> queryData = null, Action<HttpClient> buildHeaders =null)
        {
            var httpClient = new HttpClient();
            httpClient = BuildHeader(ref httpClient);
            buildHeaders?.Invoke(httpClient);
            if (queryData != null)
                url = BuildUriQuery(url, queryData);

            var responseMessage = await httpClient.PostAsync(new Uri(url), new HttpFormUrlEncodedContent(data));
            return await responseMessage.Content.ReadAsStringAsync();
        }


        private static HttpClient BuildHeader(ref HttpClient httpClient)
        {
            httpClient.DefaultRequestHeaders.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("*/*"));
            httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new HttpContentCodingWithQualityHeaderValue("gzip"));
            httpClient.DefaultRequestHeaders.UserAgent.Add(new HttpProductInfoHeaderValue("NativeHost"));
            return httpClient;
        }

        private static string BuildUriQuery(string url, IEnumerable<KeyValuePair<string, string>> queryData)
        {
            var baseUri = new UriBuilder(url);

            string query;
            using (var content = new FormUrlEncodedContent(queryData))
            {
                query = content.ReadAsStringAsync().Result;
            }

            if (baseUri.Query != null && baseUri.Query.Length > 1)
                baseUri.Query = baseUri.Query.Substring(1) + "&" + query;
            else
                baseUri.Query = query;

            return baseUri.ToString();
        }

    }
}
